/**
 * 
 */
package com.duowan.cms.common.webapp.listener;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.springframework.web.util.Log4jConfigListener;

import com.duowan.cms.common.exception.BaseUncheckedException;

/**
 * 自定义的log4j配置文件监听器，log4j.xml的可以使用spring加载的占位符,用来实现log4j的日志文件可以在自定义的配置(logs.properties)文件中配置
 * 
 * @author coolcooldee
 *
 */
public class ExtendedSpringLog4jConfigListener extends Log4jConfigListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        setLogProps2SysProps(getDefaultLogProps(event.getServletContext()));
        super.contextInitialized(event);
    }

    /**
     * 从web.xml中的log4jConfigProperties配置获取logs.properties位置，读取配置中的所有内容到Properties对象，配置文件没有则不加载
     * @param servletContext
     * @return
     */
    private Properties getDefaultLogProps(ServletContext servletContext) {
        String logFile = servletContext.getInitParameter("log4jConfigProperties");
        Properties props = new Properties();
        if (logFile == null || "".equals(logFile)) {
            return props;
        }
        InputStream logfileInputStream = servletContext.getResourceAsStream(logFile);
        if (logfileInputStream == null) {
            throw new BaseUncheckedException("资源文件不存在[log4jConfigProperties=" + logFile + "]");
        }

        InputStream in = new BufferedInputStream(logfileInputStream);
        try {
            props.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props;
    }

    /**
     * 
     * @param logProps
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void setLogProps2SysProps(Properties logProps) {
        if (logProps.isEmpty())
            return;
        Iterator itr = logProps.entrySet().iterator();
        while (itr.hasNext()) {
            Entry<String, String> e = (Entry<String, String>) itr.next();
            System.setProperty(e.getKey(), e.getValue());
        }
    }
}
